﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Media;
using System.Threading;

using Utilities.IO;
using Utilities.Media.Audio;
using Utilities.Media.Containers;
using Utilities.Media.Containers.Wav;

namespace Utilities.Media
{
    public class AudioPlayer
    {
        public AudioStream Stream { get; protected set; }
        public TimeSpan BufferDuration { get; set; }

        private SoundPlayer soundPlayer;
        private Queue<AudioBuffer> bufferQueue;

        private QueueStream queueStream;
        private WavContainer wavContainer;

        public AudioPlayer()
        {
            // Check OS

            BufferDuration = new TimeSpan(0, 0, 1);

            bufferQueue = new Queue<AudioBuffer>();
            queueStream = new QueueStream();
        }

        public void Play(AudioStream stream)
        {
            Stream = stream;
            wavContainer = new WavContainer(queueStream, stream.NumChannels, stream.SampleRate, stream.BitsPerSample, AudioFormat.PCM);

            new Thread(BufferThread).Start();

            soundPlayer = new SoundPlayer(queueStream);
            soundPlayer.Play();
        }

        private void BufferThread()
        {
            wavContainer.WriteHeader();

            while (true)
            {
                while (bufferQueue.Sum(b => b.Duration) < BufferDuration)
                {
                    AudioBuffer buffer = Stream.ReadBuffer();
                    bufferQueue.Enqueue(buffer);
                    queueStream.Write(buffer.Data, 0, buffer.Data.Length);
                }
                Thread.Sleep(100);
            }
        }
    }
}
